package com.sun.test.controller;

import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author zhangquanwei
 * @version 1.0
 * @date 2024-12-20 11:23
 */
@Controller
@RequestMapping("/file")
public class UploadController {
    private final static String FILE_UPLOAD_PATH = "D:\\data\\";
    //private final static String FILE_UPLOAD_PATH = "/home/project/upload/";

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@Param("file") MultipartFile file){
        if (file.isEmpty()) {
            return "文件不能为空";
        }
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random random = new Random();
        //生成临时文件名
        String newFileName = format.format(new Date()) + "_" + random.nextInt(1000) + suffix;
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(FILE_UPLOAD_PATH, newFileName);
            //写入到本地或者远程阿里云
            Files.write(path, bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "图片上传成功，文件地址为:"+ newFileName;
    }
}
